from datetime import datetime, timedelta
import os

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse

from .commons import *
from .core import *
from .models import *
from datetime import datetime


def book(request):
    if request.method == 'POST':
        stu_id = request.POST.get('username')
        cookies = request.POST.get('password')
        v_code = request.POST.get('captcha')
        if len(str(v_code).strip()) != 64 or not sub(v_code, stu_id):
            return HttpResponseRedirect(reverse('book:error', args=(302,)))
        save_cook(stu_id, cookies)
        return HttpResponseRedirect(reverse('book:field', args=(int(stu_id),)))
    else:
        return render(request, 'book/index.html')


def error(request, err_no):
    if err_no == 302:
        error_message = '秘钥不存在或者数量不足.'
    elif err_no == 301:
        error_message = '选择了不合法的场次.'
    else:
        error_message = "请从首页访问."
    return render(request, 'book/404.html', {'error_message': error_message})


def check_field(request, stu_id):
    if request.method == 'GET':
        return render(request, 'book/field.html', {'selected_field': get_av_fields(), 'stu_id': stu_id})
    else:
        return HttpResponseRedirect(reverse('book:error', args=(303,)))


def add(request, stu_id, s_field):
    if request.method == 'POST':
        s_time = request.POST.get('s_time')
        if valid_field_time(s_field, int(s_time)):
            now = datetime.now()
            now += timedelta(days=2)
            # 抢球场
            m_dir = os.path.dirname(__file__)
            cookie_file = os.path.join(m_dir, 'data', str(stu_id))
            s_time = int(s_time)
            start_hours = timelines[s_time - 1].split('-')[0]
            end_hours = timelines[s_time - 1].split('-')[1]
            field = fields[s_field - 1]
            od = len(os.listdir(os.path.join(m_dir, 'data')))  # 请求间隔1s
            add_order_requests(cookie_file, start_hours, end_hours, field, od)
            save(s_field, s_time)
            return render(request, 'book/200.html',
                          {'field': fields[s_field - 1], 'time1': timelines[int(s_time) - 1], 'time2': now.date(),
                           'od': od})
        else:
            return HttpResponseRedirect(reverse('book:error', args=(301,)))


def check_time(request, stu_id):
    if request.method == 'POST':
        s_field = request.POST.get('s_field')
        return render(request, 'book/time_field.html',
                      {'selected_time': get_av_times(int(s_field)), 'stu_id': int(stu_id), 's_field': int(s_field)})
    else:
        return HttpResponseRedirect(reverse('book:error', args=(303,)))
